package com.kuaifawu.lwnlawyerclient.Fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.kuaifawu.lwnlawyerclient.Activity.LWNLognWebActivity;
import com.kuaifawu.lwnlawyerclient.Activity.MainActivity;
import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Lib.LWNZxing.camera.CameraManager;
import com.kuaifawu.lwnlawyerclient.Lib.LWNZxing.decoding.CaptureActivityHandler;
import com.kuaifawu.lwnlawyerclient.Lib.LWNZxing.decoding.InactivityTimer;
import com.kuaifawu.lwnlawyerclient.Lib.LWNZxing.view.ViewfinderView;
import com.kuaifawu.lwnlawyerclient.Lib.ToastView_custom;
import com.kuaifawu.lwnlawyerclient.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.io.IOException;
import java.util.Vector;

public class LWNSaoCodeFragment extends Fragment implements SurfaceHolder.Callback{
    @ViewInject(R.id.preview_view)
    private SurfaceView surfaceView;


    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private String saoCode="";


    LayoutInflater mInflater;
    MainActivity activity_self;

    public LWNSaoCodeFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CameraManager.init(getActivity().getApplication());
        hasSurface = false;
        inactivityTimer = new InactivityTimer(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mInflater = inflater;
        View rootView = inflater.inflate(R.layout.fragment_sao_code, container, false);

        viewfinderView = (ViewfinderView)rootView.findViewById(R.id.viewfinder_view);

        ViewUtils.inject(this, rootView);
        return rootView;
    }

    public void LoadSaoCodeDataWithActivity(MainActivity activity_main) {
        activity_self = activity_main;
    }

    @Override
    public void onResume() {
        super.onResume();
       // MobclickAgent.onPageStart("MainScreen");
     //   MobclickAgent.onResume(getActivity());
        SurfaceHolder surfaceHolder = surfaceView.getHolder();

        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getActivity().getSystemService(getActivity().AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    @Override
    public void onPause() {
        super.onPause();
       // MobclickAgent.onPageEnd("MainScreen");
        //MobclickAgent.onPause(getActivity());
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    public void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    /**
     * Handler scan result
     * @param result
     * @param barcode
     */
    private String resultString="";
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        resultString = result.getText();
        //FIXME
        if (resultString.equals("")) {
            Toast.makeText(getActivity(), "扫码失败!", Toast.LENGTH_SHORT).show();
        }else {
            // Toast.makeText(CaptureActivity.this, "成功", Toast.LENGTH_SHORT).show();
            try{
                JSONObject jsonObject = new JSONObject(resultString);
                saoCode = jsonObject.getString("code");
                saveCode("-1",saoCode);
            }catch (Exception e){
                e.printStackTrace();
                saoCode="";
                Intent intent=new Intent(getActivity(), LWNLognWebActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("code",saoCode);
                intent.putExtras(bundle);
                startActivityForResult(intent, 300);
            }
        }
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;
    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator)getActivity().getSystemService(getActivity().VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    private void saveCode(String stu, final String code){
        final ProgressDialog proDialog = android.app.ProgressDialog.show(getActivity(), "", "加载中，请稍候...");
        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        if(!center.checkNetworkState(getActivity())) {

            ToastView_custom toast = new ToastView_custom(getActivity());
            toast.showCustom(getActivity(),"检查网络，稍后重试");
            proDialog.dismiss();
            return;
        }
        HttpUtils http=center.getUtils();
        String string_url = center.getInstance().getCode(stu, code, getActivity());
        http.configCurrentHttpCacheExpiry(0);
        http.send(HttpRequest.HttpMethod.GET,string_url,new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                proDialog.dismiss();
                try{

                    JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                    String string_code = jsonObject.getString("code");
                    String string_msg=jsonObject.getString("msg");
                    Intent intent=new Intent(activity_self, LWNLognWebActivity.class);
                    Bundle bundle=new Bundle();
                    switch (string_code) {
                        case "10000":
                            bundle.putString("code",saoCode);
                            intent.putExtras(bundle);
                            activity_self.startActivityForResult(intent, 300);

                            break;
                        default:
                            saoCode="";
                            bundle.putString("code",saoCode);
                            intent.putExtras(bundle);
                            getActivity().startActivityForResult(intent, 300);
                            break;
                    }

                }catch (Exception e){
                    e.printStackTrace();
                    saoCode="";
                    Intent intent=new Intent(getActivity(), LWNLognWebActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putString("code",saoCode);
                    intent.putExtras(bundle);
                    getActivity().startActivityForResult(intent, 300);
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                proDialog.dismiss();
                saoCode="";
                Intent intent=new Intent(getActivity(), LWNLognWebActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("code",saoCode);
                intent.putExtras(bundle);
                getActivity().startActivityForResult(intent, 300);
            }
        });
    }
}
